// import fileSaver from "file-saver";
const fileSaver = require("file-saver");
import Utils from "./utils.js";
/**
 *
 * @param {Array} data 导出数据
 * @param {Array} title 标题[{key:"",name:"",enum:{1:""},type:time|enum,child:""}] 枚举用来识别是否有状态/类型,child:用来识别子级对象
 * @param {string} fileName  文件名
 */
let excel = function(data, title, fileName) { 
  let exportContent = "\uFEFF";
  let content = "";
  let tStr = "";
  title.forEach(t => {
    if (tStr == "") tStr = t.name;
    else tStr += "," + t.name;
  });
  content += tStr + "\n";

  data.forEach(item => {
    let body = "";
    title.forEach(item2 => {
      let value = "";
      //判断是否取子级对象
      if (item2.child) {
        if (item[item2.child]) {
          value = item[item2.child][item2.key];
        }
      } else {
        value = item[item2.key];
      }
      if (typeof value != "undefined") {
        if (item2.type == "time") {
          let str = value
            ? "\t" + Utils.FormatTime("yyyy-MM-dd hh:mm:ss", value)
            : "";
          if (body == "") body = str;
          else body += "," + str;
        } else if (item2.type == "enum") {
          let _enum = item2.enum;
          let str = _enum[value];
          if (body == "") body = str;
          else body += "," + str;
        } else {
          value = "\t" + value;
          value = value.replace(/,/g, "，");
          let str = value ? value : "";
          if (body == "") body = str;
          else body += "," + str;
        }
      } else {
        if (body == "") body = "";
        else body += "," + "";
      }
    });
    content += body + "\n";
  });
  let blob = new Blob([exportContent + content], {
    type: "text/plain;charset=utf-8"
  });
  fileSaver.saveAs(blob, fileName + ".csv");
};
export default excel;
